<template>
  <div class="video-wrapper">
    <!-- 视频容器 -->
    <div id="video-container">
      <!-- 视频画面会在这里渲染 -->
    </div>
    
    <!-- 控制栏 -->
    <div class="video-controls">
      <div class="control-left">
        <!-- 抓拍按钮 -->
        <el-button 
          size="small" 
          type="primary" 
          plain 
          @click="handleCapture"
          :loading="capturing"
        >
          <el-icon><Camera /></el-icon>
          <span>抓拍</span>
        </el-button>
        
        <!-- 历史记录按钮 -->
        <el-button
          size="small"
          type="info"
          plain
          @click="showHistory = true"
        >
          <el-icon><Picture /></el-icon>
          <span>历史记录</span>
        </el-button>
      </div>
    </div>
    
    <!-- 加载和错误提示 -->
    <div v-if="loading" class="loading-mask">
      <div class="loading-spinner"></div>
    </div>
    <div v-if="error" class="error-message">{{ error }}</div>

    <!-- 抓拍预览弹窗 -->
    <el-dialog
      v-model="showPreview"
      title="抓拍预览"
      width="50%"
      :before-close="handleClosePreview"
    >
      <div class="capture-preview">
        <img :src="previewUrl" v-if="previewUrl" class="preview-image"/>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClosePreview">关闭</el-button>
          <el-button type="primary" @click="handleDownloadImage">
            下载图片
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 历史抓拍记录抽屉 -->
    <el-drawer
      v-model="showHistory"
      title="历史抓拍记录"
      direction="rtl"
      size="60%"
      :destroy-on-close="false"
    >
      <CaptureHistory ref="captureHistoryRef" />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import EZUIKit from 'ezuikit-js'
import { getYsToken } from '../api/ys'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Camera, Picture } from '@element-plus/icons-vue'
import CaptureHistory from './CaptureHistory.vue'

const loading = ref(false)
const error = ref('')
const player = ref<any>(null)
const isPlaying = ref(true)
const isMuted = ref(false)
const isRecording = ref(false)
const isTalking = ref(false)

// 添加时间相关的状态
const currentTime = ref('')
const currentDate = ref('')

// 添加历史记录相关状态
const showHistory = ref(false)
const capturing = ref(false)

// 添加预览相关状态
const showPreview = ref(false)
const previewUrl = ref('')

// 添加历史记录组件的ref
const captureHistoryRef = ref()

const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString()
  currentDate.value = now.toLocaleDateString()
}

// 播放器控制方法
const togglePlay = () => {
  if (player.value) {
    isPlaying.value ? player.value.pause() : player.value.play()
    isPlaying.value = !isPlaying.value
  }
}

const toggleSound = () => {
  if (player.value) {
    isMuted.value ? player.value.openSound() : player.value.closeSound()
    isMuted.value = !isMuted.value
  }
}

const toggleRecord = () => {
  if (player.value) {
    isRecording.value ? player.value.stopRecord() : player.value.startRecord()
    isRecording.value = !isRecording.value
  }
}

const toggleTalk = () => {
  if (player.value) {
    isTalking.value ? player.value.stopTalk() : player.value.startTalk()
    isTalking.value = !isTalking.value
  }
}

const capturePicture = async () => {
  try {
    const accessToken = localStorage.getItem('ysToken')
    console.log('当前token:', accessToken)

    if (!accessToken || accessToken === 'undefined') {
      throw new Error('未获取到有效的萤石云token')
    }

    // 检查今日抓拍次数
    const today = new Date().toDateString()
    const captureCount = parseInt(localStorage.getItem(`captureCount_${today}`) || '0')
    
    if (captureCount >= 100) {
      throw new Error('今日抓拍次数已达上限(100次)，请明天再试')
    }

    // 发送抓拍请求
    const params = new URLSearchParams()
    params.append('accessToken', accessToken)
    params.append('deviceSerial', 'AB9831171')
    params.append('channelNo', '1')
    params.append('quality', '1')

    console.log('发送抓拍请求参数:', Object.fromEntries(params))

    const response = await axios.post('/api/ys/capture', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })

    console.log('抓拍响应:', response.data)

    if (response.data.code === 200) {
      if (response.data.data?.code === '200') {
        // 更新抓拍次数
        localStorage.setItem(`captureCount_${today}`, (captureCount + 1).toString())
        ElMessage.success(`抓拍成功(今日第${captureCount + 1}次)`)
        return response.data.data.data.picUrl
      } else if (response.data.data?.code === '10028') {
        throw new Error('今日抓拍次数已达萤石云平台限制，请明天再试')
      }
      throw new Error(response.data.data?.msg || '抓拍失败')
    }
    throw new Error('请求失败')
  } catch (error) {
    console.error('抓拍失败:', error)
    ElMessage.error(error.message || '抓拍失败')
    return null
  }
}

const fullScreen = () => {
  player.value?.fullScreen()
}

const init = async () => {
  try {
    loading.value = true
    error.value = ''

    const res = await getYsToken()
    if (res && res.code === 200) {
      const token = res.data?.data?.accessToken
      
      player.value = new EZUIKit.EZUIKitPlayer({
        id: 'video-container',
        accessToken: token,
        url: 'ezopen://open.ys7.com/AB9831171/1.hd.live',
        template: 'simple',
        autoplay: true
      })
    } else {
      throw new Error('获取萤石云token失败')
    }
  } catch (err) {
    error.value = '初始化失败'
    console.error(err)
  } finally {
    loading.value = false
  }
}

// 修改抓拍方法
const handleCapture = async () => {
  try {
    capturing.value = true
    const picUrl = await capturePicture()
    if (picUrl) {
      // 显示预览
      previewUrl.value = picUrl
      showPreview.value = true
      
      // 添加到历史记录
      captureHistoryRef.value?.addNewCapture(picUrl)
      
      ElMessage.success('抓拍成功')
    }
  } catch (error) {
    console.error('抓拍失败:', error)
    ElMessage.error('抓拍失败')
  } finally {
    capturing.value = false
  }
}

// 关闭预览
const handleClosePreview = () => {
  showPreview.value = false
  previewUrl.value = ''
}

// 下载图片
const handleDownloadImage = async () => {
  if (previewUrl.value) {
    try {
      const response = await fetch(previewUrl.value)
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `capture_${new Date().getTime()}.jpg`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(url)
      ElMessage.success('下载成功')
    } catch (error) {
      console.error('下载失败:', error)
      ElMessage.error('下载失败')
    }
  }
}

onMounted(() => {
  updateTime()
  setInterval(updateTime, 1000)
  init()
})

defineExpose({
  capturePicture
})
</script>
<style scoped>
.video-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

#video-container {
  width: 100%;
  height: 100%;
  background: #000;
}

/* 修改萤石云播放器的默认样式 */
:deep(.ezuikit-video),
:deep(.ezuikit-video video) {
  width: 100% !important;
  height: 100% !important;
  object-fit: fill;
}

.control-right {
  display: flex;
  gap: 2px;
  margin-left: 4px;
}

.control-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: none;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.8;
  transition: opacity 0.2s;
}

.control-btn:hover {
  opacity: 1;
}

/* 加载和错误提示样式 */
.loading-mask,
.error-message {
  position: absolute;
  inset: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0,0,0,0.7);
  color: white;
  z-index: 20;
}

.error-message {
  padding: 12px 24px;
  background: rgba(255,0,0,0.7);
  border-radius: 4px;
}

/* 隐藏萤石云播放器右上角的工具栏 */
:deep(.ezuikit-video) {
  width: 100% !important;
  height: 100% !important;
}

:deep(.ezuikit-video video) {
  width: 100% !important;
  height: 100% !important;
  object-fit: fill;
}

/* 隐藏萤石云播放器原有的控制栏和工具栏 */
:deep(.ezuikit-video .audio-controls),
:deep(.ezuikit-video .video-controls),
:deep(.ezuikit-video .toolbar),
:deep(.ezuikit-video .handle),
:deep(.ezuikit-video .window-container) {
  display: none !important;
}

:deep(.ezuikit-video .toolbar),
:deep(.ezuikit-video .handle) {
  display: none !important;
}

.video-controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px;
  background: rgba(0,0,0,0.6);
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .control-left {
    display: flex;
    gap: 8px;
  }

  :deep(.el-button) {
    display: flex;
    align-items: center;
    gap: 4px;
    background: rgba(0,21,41,0.6);
    border-color: rgba(0,255,255,0.3);
    
    &:hover {
      background: rgba(0,228,255,0.1);
      border-color: #00e4ff;
    }

    .el-icon {
      font-size: 16px;
    }
  }
}

/* 添加预览相关样式 */
.capture-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  
  .preview-image {
    max-width: 100%;
    max-height: 60vh;
    object-fit: contain;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-dialog) {
  background: rgba(0,21,41,0.95);
  border: 1px solid rgba(0,255,255,0.1);
  
  .el-dialog__header {
    border-bottom: 1px solid rgba(0,255,255,0.1);
    margin-right: 0;
    padding: 12px 20px;
    
    .el-dialog__title {
      color: #00e4ff;
    }
  }
  
  .el-dialog__body {
    padding: 20px;
  }
  
  .el-dialog__footer {
    border-top: 1px solid rgba(0,255,255,0.1);
    padding: 12px 20px;
  }
}
</style>

